/*
 * @Author: wangzm
 * @Date: 2020-03-02 15:40:30
 * @LastEditors: wjk
 * @LastEditTime: 2020-12-31 14:42:00
 * @Description: common
 */
import Vue from 'vue'
import { mapActions, mapState } from 'vuex'
// #ifdef H5
import Bridge from './JSBridge'
// #endif

let registerHandlerFlag = true

Vue.mixin({
  onPageScroll(res) {
    uni.$emit('scroll', res)
  },
  computed: {
    ...mapState([
      'systemInfo',
      'token',
      'userInfo'
    ])
  },
  data() {
  	return {
      isInApp:false,//是否在app内
  	}
  },
  async onPullDownRefresh() {
    if (this.token) {
      const page = this.$prePage(1, 'route')
      const baseView = this.$children[0]
      const systemInfo = uni.getSystemInfoSync()
      if (process.env.VUE_APP_PLATFORM === 'mp-weixin') {
        if (baseView.customPage.indexOf(page) !== -1) {
          baseView.marginTop = `${systemInfo.statusBarHeight + 44}px`
        } else {
          baseView.marginTop = '0'
        }
      } else {
        baseView.marginTop = '6rpx'
      }
      if(baseView.fetchRemind){
       await baseView.fetchRemind() 
      }
      if(baseView.getRemind){
        baseView.getRemind()
      }
    }
  },
  async onLoad(options) {
    // #ifdef H5
    if(Bridge.isInApp){
      this.isInApp=true;
    }
    // #endif
    const share_code = this.$queryPageParam(options, 'share_code')
    if (share_code) {
      uni.setStorageSync('share_code', share_code)
    }
    /* eslint-disable */
    // 埋点设置第一个进入页面
    const pages = getCurrentPages()
    const page = pages[pages.length-1]
    uni.getStorage({
      key: 'isOnLaunch',
      success: () => {
        uni.setStorage({
          key: 'firstEnterPage',
          data: page.route
        })
      }
    })
    /* eslint-disable-end */

    // #ifdef H5
    if(registerHandlerFlag){
      this.registerHandler()
    }
    if (options.token || (options.user_token && options.user_token!=='null')) {
      this.SET_TOKEN(options.token || options.user_token)
      await this.GetUserInfo().then(() => {
        if (this.app_interactive_data) {
          this.app_interactive_data(options)
        }
        return true
      }).catch(() => {
        return false
      })
    } else if(Bridge.isInApp){ // 与APP有交互的页面
      const data = {
        type: 'getUser',
        data: {
          need_login: this.page_need_login ? true : false
        }
      }
      Bridge.callHandler(data, async (res) => {
        if(res){
          const resData = JSON.parse(res)
          console.log('appData', resData)
          if(!this.token){
            // 下面代码是兼容代码，过几个版本后，可以替换成上面的代码
            if(resData.userInfo){
              this.SET_USER(resData)
            } else {
              this.SET_USER({
                token: resData.token,
                userInfo: resData
              })
            }
            await this.GetUserInfo()
          }
        }
        if(this.app_interactive_data){
          this.app_interactive_data(options)
          return
        }
      })
    } else if (this.app_interactive_data) {
      this.app_interactive_data(options)
    }
    // #endif

    // #ifdef MP-WEIXIN
    if (this.app_interactive_data) {
      this.app_interactive_data(options)
    }
    // #endif
  },

  onShow() {
    if(this.initShare){
      // console.log('onShow: start initShare')
      this.initShare()
    } else {
      this.hideShare()
    }
  },

  methods: {
    ...mapActions([
      'SET_USER',
      'SET_TOKEN',
      'GetUserInfo'
    ]),
    registerHandler() {
      // #ifdef H5
      if(Bridge.isInApp){
        console.log('registerHandler')
        registerHandlerFlag = false
        // 兼容旧版本APP 开始
        window.__BSNLAPPCallHandler__ = (str) => {
          return this.appCallJs(str)
        }
        // 兼容旧版本APP 结束
        Bridge.registerHandler('__BSNLAPPCallHandler__', (str, responseCallback) => {
          this.appCallJs(str, responseCallback)
        })
      }
      // #endif
    },
    appCallJs(str, responseCallback) {
      if (str) {
        const data = JSON.parse(str)
        let resStr = '{}'
        if(data.type==='share'){
          resStr = JSON.stringify(this.shareOption || {})
        }

        console.log('app 调用 js:', data, responseCallback, resStr)
        if(responseCallback){
          responseCallback(resStr)
        } else {
          return resStr
        }
      }
    },
    hideShare() {
      // console.log('hideShare')
      // #ifdef MP-WEIXIN
      uni.hideShareMenu() // 微信小程序隐藏分享菜单
      // #endif
      //-----------------------------------------------------
      // #ifdef H5
      if(Bridge.isInWeChat){
        Bridge.hideWeChatMenu(!!this.showOpenBrowserMenu) // 微信内置浏览器隐藏分享菜单
      } else if (Bridge.isInApp){
        Bridge.callHandler({
          type: 'share',
          data: {
            is_button_show: false
          }
        })
      }
      // #endif
    },
    showShare() {
      // #ifdef MP-WEIXIN
      this.shareOption.page_path = this.$queryShareOption({}, this.shareOption).path
      uni.showShareMenu()
      // #endif

      // #ifdef H5
      // console.log(this.shareOption, 123)
      this.shareOption = this.$queryShareOption({}, this.shareOption)
      // console.log('share_url--', this.shareOption.share_url)
      this.shareOption.is_button_show = true
      this.shareOption.is_dialog_show = true
      if(Bridge.isInWeChat){
        const initData = {
          title: this.shareOption.share_title,
          link: this.shareOption.share_url,
          imgUrl: this.shareOption.share_icon,
          desc: this.shareOption.share_content
        }

        Bridge.initWeChatShare(initData) // 微信内置浏览器配置分享内容
      } else if (Bridge.isInApp){
        Bridge.callHandler({
          type: 'share',
          data: {
            is_button_show: true
          }
        })
      }
      // #endif
    },
    hello() {
      // eslint-disable-next-line
      console.log('hello is called...')
    }
  }
})
